package com.taxi.driver.module.main.home;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qianxx.utils.DateUtil;
import com.qianxx.view.dialog.ExSweetAlertDialog;
import com.qianxx.view.loadingview.BallLoading;
import com.qianxx.view.xrecyclerview.IXRecyclerViewListener;
import com.qianxx.view.xrecyclerview.XRecyclerView;
import com.taxi.driver.R;
import com.taxi.driver.common.BaseFragment;
import com.taxi.driver.config.DriverType;
import com.taxi.driver.data.entity.OrderHomeStatusEntity;
import com.taxi.driver.event.OrderEvent;
import com.taxi.driver.module.main.home.dagger.DaggerHomeComponent;
import com.taxi.driver.module.main.home.dagger.HomeModule;
import com.taxi.driver.module.main.mine.message.details.MessageDetailsActivity;
import com.taxi.driver.module.main.mine.wallet.MyWalletActivity;
import com.taxi.driver.module.order.detail.OrderDetailActivity;
import com.taxi.driver.module.order.pool.PoolActivity;
import com.taxi.driver.module.vo.HomePageVO;
import com.taxi.driver.module.vo.MessageVO;
import com.taxi.driver.module.vo.OrderSummaryVO;
import com.taxi.driver.socket.SocketData;
import com.taxi.driver.util.Navigate;
import com.taxi.driver.widget.TextViewPlus;
import com.taxi.driver.widget.dialog.ConfirmDialog;
import com.taxi.driver.widget.dialog.TwoSelectorDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 功能描述：主页
 */
public class HomeFragment extends BaseFragment implements HomeContract.View {

    @BindView(R.id.tv_notice)
    TextViewPlus mTvNotice;
    @BindView(R.id.x_recycler_view)
    XRecyclerView mXRecyclerView;
    @BindView(R.id.layout_notice)
    LinearLayout mLayoutNotice;
    @BindView(R.id.ball)
    BallLoading mBallLoading;

    private int mSocketFailCount = 0;
    private int mLocationFailCount = 0;
    private boolean isNet = true;
    private boolean isSocket = true;
    private AppointmentAdapter mAppointmentAdapter;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Inject
    HomePresenter mPresenter;

    private ViewHolder mViewHolder;
    private HomeAdapter mAdapter;
    private ExSweetAlertDialog mOngoingDialog;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, mView);

        mPresenter.onCreate();
        /* 初始化列表 */
        initView();
        initExtend();
        initListener();

        return mView;
    }

    private void initView() {
        mAdapter = new HomeAdapter(getContext());
        mXRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mXRecyclerView.setAdapter(mAdapter);
    }

    private void initExtend() {
        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_home_top, mXRecyclerView, false);
        mViewHolder = new ViewHolder(headerView);
        mViewHolder.mTvTopInfo.setText(getCurrentDate());

        mAppointmentAdapter = new AppointmentAdapter(getActivity());
        mViewHolder.mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mViewHolder.mRecyclerView.setAdapter(mAppointmentAdapter);

        mViewHolder.mLayoutTop.setOnClickListener(v -> Navigate.openAssenssmentStatisitcal(getContext()));
        mViewHolder.mTvOrderPool.setOnClickListener(v -> PoolActivity.start(getContext()));

        mAppointmentAdapter.setOnItemClickListener((position, view, item) -> openOrderDetail(item.uuid));

        mAdapter.addHeaderView(headerView);
    }

    private void initListener() {
        mXRecyclerView.setXRecyclerViewListener(new IXRecyclerViewListener() {
            @Override
            public void onRefresh() {
                mPresenter.reqWorkInfo();
                mPresenter.getAppointmentList();
                mPresenter.canGrapOrders();
                mPresenter.refresh();
            }

            @Override
            public void onLoadMore() {
                mPresenter.loadMore();
            }
        });

        mAdapter.setOnItemClickListener((position, view, item) -> {
            if (item.type == 1) {
                MessageDetailsActivity.start(getContext(), item);
            } else if (item.type == 3) {
                MyWalletActivity.start(getContext(), item.uuid, item.status);
            }
        });

        mAdapter.setOnClickListener(R.id.img_delete, (position, view, item) -> mPresenter.deleteMsg(position, item.uuid));

        mXRecyclerView.onRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.subscribe();
        mPresenter.refresh();
    }

    @Override
    public void onPause() {
        super.onPause();
        mPresenter.unsubscribe();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresenter.onDestory();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        DaggerHomeComponent.builder()
                .appComponent(getAppComponent())
                .homeModule(new HomeModule(this))
                .build().inject(this);
    }

    @Override
    public void setList(List<MessageVO> vos) {
        mXRecyclerView.refreshComplete();
        mAdapter.setAll(vos);
        if (vos.size() <= 0) {
            mXRecyclerView.setLoadHide();
        }
    }

    @Override
    public void setListFailed() {
        mXRecyclerView.loadFailed();
    }

    @Override
    public void appendList(List<MessageVO> vos) {
        if (vos.size() < 10) {
            mXRecyclerView.setLoadHide();
        } else {
            mXRecyclerView.setLoadComplete(false);
        }
        mAdapter.addAll(vos);
    }

    @Override
    public void deleteSuccess(int position) {
        mAdapter.remove(position);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showHomePageInfo(HomePageVO vo) {
        mViewHolder.mTvLeft.setText(vo.orderCount == null ? 0 + "" : vo.orderCount + ""); //订单数
        mViewHolder.mTvRight.setText(vo.orderIncome == null ? 0 + "" : String.format("%.01f", vo.orderIncome));
        String onlineTime = vo.getStrOnlineTime();
        String notice = getCurrentDate() + "，已出车" + onlineTime;
        mViewHolder.mTvTopInfo.setText(notice);
    }

    @Override
    public void openOrderOngoing(String orderUuid) {
//        Navigate.openOrderOngoing(getContext(), orderUuid);
        OrderDetailActivity.start(getActivity(), orderUuid,110);
    }

    @Override
    public void openOrderDetail(String orderUuid) {
        OrderDetailActivity.start(getActivity(), orderUuid,0);
    }

    @Override
    public void showNetworkNotice(boolean disconnect) {
        isNet = disconnect;
        mLayoutNotice.setVisibility(disconnect ? View.GONE : View.VISIBLE);
        mTvNotice.setText(getString(R.string.network_disconnect));
    }

    @Override
    public void showSocketNotice(boolean socket) {
        if (!isNet) {
            return;
        }
        isSocket = socket;
        if (socket) {
            mSocketFailCount = 0;
        } else {
            mSocketFailCount++;
        }
        mLayoutNotice.setVisibility(socket ? View.GONE : View.VISIBLE);
        if (mSocketFailCount < 60) {
            mTvNotice.setText(R.string.socket_failed);
        } else {
            mTvNotice.setText(R.string.socket_offline);
        }
    }

    @Override
    public void showLocationNotice(boolean location) {
        if (!isNet || !isSocket) {
            return;
        }
        if (location) {
            mLocationFailCount = 0;
        } else {
            mLocationFailCount++;
        }
        mLayoutNotice.setVisibility(location ? View.GONE : View.VISIBLE);
        if (mLocationFailCount < 60) {
            mTvNotice.setText(R.string.location_failed);
        } else {
            mTvNotice.setText(R.string.location_failed_again);
        }
    }

    @Override
    public void showHomeStatus(OrderHomeStatusEntity entity) {
        int titleRes = R.string.you_have_the_order_has_been_waiting_for_payment_for_a_long_time;
        if (entity.status == 1 || entity.status == 2) {
            EventBus.getDefault().post(new OrderEvent(OrderEvent.ORDER_COMPLETE, false));
        } else {
            EventBus.getDefault().post(new OrderEvent(OrderEvent.ORDER_COMPLETE, true));
        }
        switch (entity.status) {
            case 1://有订单（预约单）已超过出发时间（等待接驾未出发）
                showAppointmentDialog(entity.orderUuid, R.string.you_order_has_been_departure_time_please_immediately_processing, R.string.order_review);
                break;
            case 2://有订单正在进行中，已出发，未确认金额
                openOrderOngoing(entity.orderUuid);
                break;
            case 3://有订单长时间未支付（金额确认后超过1小时未支付）
                if ( mPresenter.driverType() == DriverType.SPECIAL) {
                    titleRes = R.string.you_have_the_order_has_been_waiting_for_payment_for_a_long_time;
                }
                showPromptDialog(entity.orderUuid, titleRes, R.string.later, R.string.order_review);
                break;
            case 4://有订单（预约单）即将开始（10分钟内）
                if ( mPresenter.driverType() == DriverType.SPECIAL) {
                    titleRes = R.string.you_have_order_is_about_to_begin_please_prepared_to_welcome;
                }
                showPromptDialog(entity.orderUuid, titleRes, R.string.later, R.string.order_review);
                break;
            default:
                if (mOngoingDialog != null) {
                    mOngoingDialog.dismiss();
                }
                break;
        }
    }

    @Override
    public void appointmentList(List<OrderSummaryVO> vos) {
        mAppointmentAdapter.setAll(vos);
    }

    @Override
    public void orderCancelled(SocketData data) {
        if (mOngoingDialog != null) {
            mOngoingDialog.dismiss();
        }

        mOngoingDialog = new TwoSelectorDialog(getActivity(), data.title, data.content, "好的", "查看详情")
                .setConfirmClickListener(dialog -> {
                    openOrderDetail(data.orderUuid);
                    dialog.dismiss();
                })
                .setCancelClickListener(Dialog::dismiss);
        mOngoingDialog.show();
    }

    @Override
    public void orderChangedToOther(SocketData data) {
        if (mOngoingDialog != null) {
            mOngoingDialog.dismiss();
        }

        mOngoingDialog = new ConfirmDialog(getActivity(), data.title, data.content, "好的")
                .setConfirmClickListener(Dialog::dismiss);
        mOngoingDialog.show();
    }

    @Override
    public void reassign() {
        mPresenter.getAppointmentList();
    }

    @Override
    public void showOrderPool(int num) {
        if (num == 0) {
            mViewHolder.mSpace.setVisibility(View.VISIBLE);
            mViewHolder.mTvOrderPool.setVisibility(View.GONE);
        } else {
            mViewHolder.mSpace.setVisibility(View.GONE);
            mViewHolder.mTvOrderPool.setVisibility(View.VISIBLE);
            mViewHolder.mTvOrderPool.setText(getString(R.string.can_grab_orders, num));
        }
    }

    @Override
    public void showBall(boolean show) {
        mBallLoading.show(show);
    }

    private void showAppointmentDialog(String orderUuid, int titleId, int btnTextId) {
        if (mOngoingDialog != null) {
            mOngoingDialog.dismiss();
        }

        mOngoingDialog = new ConfirmDialog(getActivity(), getString(titleId), null, getString(btnTextId));
        mOngoingDialog.setConfirmClickListener(dialog -> {
            dialog.dismiss();
            openOrderDetail(orderUuid);
        });
        mOngoingDialog.show();
    }

    private void showPromptDialog(String orderUuid, int titleId, int leftBtnTextId, int rightBtnTextId) {
        if (mOngoingDialog != null) {
            mOngoingDialog.dismiss();
        }

        mOngoingDialog = new TwoSelectorDialog(getActivity(), getString(titleId), null,
                getString(leftBtnTextId), getString(rightBtnTextId));
        mOngoingDialog.setConfirmClickListener(dialog -> {
            dialog.dismiss();
            openOrderDetail(orderUuid);
        }).setCancelClickListener(Dialog::dismiss);
        mOngoingDialog.show();
    }

    private String getCurrentDate() {
        long current = System.currentTimeMillis();
        return DateUtil.transferLongToDate("MM月dd日", current) + "，" + DateUtil.getWeekOfDate(new Date(current));
    }

    class ViewHolder {

        @BindView(R.id.layout_top)
        View mLayoutTop;
        @BindView(R.id.tv_top_info)
        TextView mTvTopInfo;
        @BindView(R.id.tv_left)
        TextView mTvLeft;
        @BindView(R.id.tv_left_tag)
        TextView mTvLeftTag;
        @BindView(R.id.tv_right)
        TextView mTvRight;
        @BindView(R.id.tv_right_tag)
        TextView mTvRightTag;
        @BindView(R.id.space)
        View mSpace;
        @BindView(R.id.tv_order_pool)
        TextView mTvOrderPool;
        @BindView(R.id.recycler_view)
        RecyclerView mRecyclerView;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
